<!--
Copyright 2014 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="../lib/log.html">
<link rel="import" href="../lib/net.html">
<link rel="import" href="../lib/cqstats-util.html">

<script>
function CQStatsGraphData(name, cqStatsListPromise) {
  this.rowItemsAvailable = true;
  this._name = name;
  this._cqStatsListPromise = cqStatsListPromise;
  this._formattedDataPromise = cqStatsListPromise.then(
      this._formatCQStatsList.bind(this));
}

CQStatsGraphData.createBatch = function(
    project, intervalMinutes, names, count) {
  var cqStatsListPromise = cqStatsUtil.loadStats(
      project, intervalMinutes, names, count).catch(log);
  return names.map(function(name) {
    return new CQStatsGraphData(name, cqStatsListPromise);
  });
};

CQStatsGraphData.prototype._formatCQStatsList = function(cqStatsList) {
  var name = this._name;
  return {
    cols: ['timestamp', 'max', 'p90', 'p50', 'min', 'mean'],
    rows: cqStatsList.map(function(cqStats) {
      var stat = null;
      cqStats.stats.forEach(function(testStat) {
        if (testStat.name === name) {
          stat = testStat;
        }
      });
      // Convert timestamps to Date objects and seconds to minutes.
      return [
        new Date(cqStats.end * 1000),
        stat.max / 60,
        stat.percentile_90 / 60,
        stat.percentile_50 / 60,
        stat.min / 60,
        stat.mean / 60,
      ];
    }),
  };
}

CQStatsGraphData.prototype.get = function() {
  return this._formattedDataPromise;
};

CQStatsGraphData.prototype.rowItems = function(index) {
  var name = this._name;
  return this._cqStatsListPromise.then(function(cqStatsList) {
    var cqStats = cqStatsList[index];
    return cqStatsUtil.loadStatItems(name, cqStats.key).then(function(items) {
      // Convert seconds to minutes.
      items.forEach(function(item) { item[0] /= 60; });
      return {
        items: items,
        begin: cqStats.begin,
        end: cqStats.end,
      };
    });
  })
};
</script>
